#include <time.h>
#include "logic.h"

static void* main_thread(void* arg);
static void* conn_thread(void* arg);

void LogicServer::run(){
    while(true){
        // 检查是否连接到了dbserver
        if(m_is_client && !m_client.isConnected()){
            pthread_t t;
            pthread_create(&t, NULL, &conn_thread, this);
        }

        // 等待http端的通信
        int fd = m_server.Accept();
        printf("Accept[%d]\n", fd);
        if(fd>0){
            pthread_t t;
            pthread_create(&t, NULL, &main_thread, this);
            m_socket_map[t] = fd;
        }
    }
}

static void* conn_thread(void* arg){
    LogicServer* logic = (LogicServer*) arg;
    while(!logic->isConnectServer()){
        logic->connectServer();
        sleep(5);
    }
}

static void* main_thread(void* arg){
    pthread_t thread = pthread_self();
    LogicServer* logic = (LogicServer*)arg;
    char buf[LogicServer::STREAM_BUF_SIZE] = {0};

    sleep(2);   // 等待fd映射完成
    int fd = logic->getSocketMap(thread);
    time_t conn_start = time(0);
    while(true){
        // 接收http端数据
        int size = recv(fd, buf, LogicServer::STREAM_BUF_SIZE, 0);
        if(size > 0){
            conn_start = time(0);
            fprintf(stdout, "buf[%s]\n", buf);
            logic->handle(buf);
        }
        memset(buf, 0, LogicServer::STREAM_BUF_SIZE);
        if(time(0)-conn_start > logic->getOvertime()){
            logic->delSocketMap(thread);
            close(fd);
            fprintf(stderr, "fd[%d] is unconnected.\n", fd);
            break;
        }
    }
}
